package com.goteam.lmapp.core.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CoreClientHandler extends ChannelInboundHandlerAdapter {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private ByteBuf message;

	/**
	 * Creates a client-side handler.
	 */
	public CoreClientHandler() {
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		logger.info("client connect to server, send msg to server.");
		byte[] data = "服务器，给我一个APPLE".getBytes();
		message=Unpooled.buffer();
		message.writeBytes(data);
		ctx.writeAndFlush(message);
		
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		logger.info("recieved msg from server:" + msg);
		ReferenceCountUtil.release(msg);

	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// close the connection when an exception is raised.
		cause.printStackTrace();
		ctx.close();
	}
}
